import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/sess")
public class SessionServlet extends HttpServlet {

    private static final String SESSION_USER_KEY = "SESSION_USER_KEY";

    /**
     * 读 Session
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=utf-8");
        // 1.得到 Session [false：有会话返回 session 对象，没有会话返回null；
        //  true：有会话返回 session 对象，没有会话创建一个会话] 会话=是否登录
        HttpSession session = req.getSession(false);
        if (null == session) {
            // 没有登录
            resp.getWriter().println("抱歉，尚未登录！");
        } else {
            // 已登录,打印用户的信息
            // 2.从 Session 中得到关联对象
            User user = (User) session.getAttribute(SESSION_USER_KEY);
            resp.getWriter().println("登录成功 |" + user);
        }
    }

    /**
     * 写 Session
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=utf-8");
        String result = "操作失败！";
        // 1.得到 Session
        HttpSession session = req.getSession(true);
        if (null != session) { // 得到（或创建）会话
            // 2.将用户对象存储到 session
            User user = new User();
            user.setName("admin");
            user.setPassword("amdin");
            session.setAttribute(SESSION_USER_KEY, user);
            result = "Session 写入成功！";
        }
        resp.getWriter().println(result);
    }
}